package org.tloss.games.mummy;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Table Settings<br/>
 * +---------------------+<br/>
 * | Settings |<br/>
 * +---------------------+<br/>
 * | Name: nvarchar(20)* |<br/>
 * +---------------------+<br/>
 * | Value: nvarchar(50) |<br/>
 * +---------------------+<br/>
 */
public class StorageHelperImpl extends SQLiteOpenHelper implements
		StorageHelper {

	public static final String CREATE_TABLE_SETTINGS = "CREATE TABLE SETTINGS(Name TEXT PRIMARY KEY,Value  TEXT)";
	private static final String DBNAME = "MUMMY";
	private static final int DBVERSION = 1;

	public StorageHelperImpl(Context context) {
		super(context, DBNAME, null, DBVERSION);
	}

	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_TABLE_SETTINGS);

	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	public String getConfig(String name) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor c = db.query("SETTINGS", new String[] { "Value" }, "Name =?",
				new String[] { name }, null, null, null);

		if (c != null && c.moveToFirst()) {
			return c.getString(c.getColumnIndex("Value"));
		}
		return null;
	}

	public void saveConfig(String name, String value) {
		String oldValue = getConfig(name);
		if (oldValue == null || !oldValue.equals(value)) {
			SQLiteDatabase db = this.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put("Value", value);
			db.update("SETTINGS", values, "Name = ?", new String[] { name });
		}
	}

}
